<template>
  <!-- 添加权限弹窗 -->
  <el-dialog
    v-model="centerDialogVisible"
    title="添加权限"
    width="500"
    align-center
  >
    <el-form
      ref="limitsForm"
      :model="form"
      :rules="rules"
      label-width="auto"
      style="max-width: 600px"
    >
      <el-form-item label="名称" prop="name">
        <el-input v-model="form.name" />
      </el-form-item>
    </el-form>
    <el-form-item label="权限">
      <el-tree
        ref="limitsTree"
        :data="limitsData"
        show-checkbox
        node-key="id"
        :default-checked-keys="[2, 4, 5]"
        :default-expanded-keys="[2]"
        :props="defaultProps"
    /></el-form-item>

    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="notarizeBtn(limitsForm)">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { getMenuListApi, setMenuApi, getMenuApi } from '@/api/menuAPi'
import { ElMessage } from 'element-plus'
onMounted(() => {
  getMenuList()
  getMenu()
})

const centerDialogVisible = ref(true) // 控制弹窗显示
const limitsForm = ref() // from的ref字段
const limitsTree = ref() // tree的ref字段
const limitsData = ref([]) // tree数据

// form表单绑定字段
const form = reactive({
  name: '',
})
// form表单定义规则
const rules = reactive({
  name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
})

// 获取tree数据方法
const getMenuList = async () => {
  const res = await getMenuListApi()
  limitsData.value = res?.data
}

// 获取菜单权限列表方法
const getMenu = async () => {
  const res = await getMenuApi({
    pageNum: '1',
    pageSize: '10',
  })
  console.log(res, '123456')
}

// 菜单权限数据修改方法
const setMenu = async () => {
  const res = await setMenuApi({
    id: '',
    permissions: JSON.stringify(limitsTree.value.getCheckedKeys()) || '',
    name: form.name,
  })
  if (res?.code === 10000) {
    ElMessage({
      message: '权限修改成功',
      type: 'success',
    })
    centerDialogVisible.value = false
  }
}

// 弹窗按下确认按钮的方法
const notarizeBtn = async (value) => {
  if (!value) return
  await value.validate((valid, fields) => {
    if (valid) {
      setMenu()
    } else {
      console.log('error submit!', fields)
    }
  })
}
</script>
<style scoped lang="less"></style>
